#!/usr/bin/env
#-*- encoding:utf-8 -*-

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class PageInfo():
    def __init__(self, class_obj, args):
        self.class_obj = class_obj
        self.args = args

class FDBWizard(QObject):
    sigPageSwitched = pyqtSignal(str)  # 切换到了某页面

    def __init__(self,stage,parent = None):
        super(FDBWizard,self).__init__(parent)
        self.stage = stage
        self.current_page = None
        self.current_page_name = None

        self.pages = {}

        self.widgets = {}

    def add_page(self,name,page,*args):
        # if isinstance(page,QWidget):
        page_info = PageInfo(page,args)
        self.pages[name] = page_info
        # else:
        #     raise TypeError

    def get_current_page(self):
        return self.current_page
    def get_current_page_name(self):
        return self.current_page_name

    def get_page(self, page_name):
        if page_name in self.widgets:
            return self.widgets[page_name]
        return None

    def goto_page(self, name, reinit = False, init_arg = (), tell_me_new=False, switch=None, *args, **kwargs):
        """
        :param reinit 是重新执行初始化,注意这并不会重新构造这个页面,这是再次调用他的init函数
        :param switch 切页的效果
               "crush" 挤压（新出现在kwargs中direction指明）
        :param tell_me_new 告诉调用者，这是新创造的页面吗？
        """
        print("wizard: {0}, goto page".format(self), name)
        page_info = self.pages.get(name)
        widget_instance = None
        newed = False  # 这个页面是靠新创建出来的吗？

        if name in self.widgets:
            widget_instance = self.widgets[name]
        elif name == "__previous__": # current page's previous page
            if hasattr(self.current_page, "__previous_page__") is False:
                if tell_me_new is True:
                    return self.current_page, newed
                else:
                    return self.current_page
            widget_instance = self.current_page.__previous_page__
            if widget_instance is None:
                if tell_me_new is True:
                    return self.current_page, newed
                else:
                    return self.current_page

            self.current_page.setVisible(False)
            self.current_page = widget_instance
            for widget_page_name, widget_page_info in self.pages.items():
                if isinstance(widget_instance, widget_page_info.class_obj):
                    name = widget_page_name
                    print("previous page name is:", name)
                    self.current_page_name = name
                    break
            self.current_page.setVisible(True)
            self.sigPageSwitched.emit(name)

            if reinit is True:
                if isinstance(init_arg, tuple) is False:
                    init_arg = (init_arg, )
                if len(init_arg) > 0:
                    py = "widget_instance.init("
                    for i in range(0, len(init_arg)):
                        py += "init_arg[{0}], ".format(i)
                    py = py[:-1]
                    py += ")"
                    exec(py)
                else:
                    widget_instance.init()
            if tell_me_new is True:
                return self.current_page, newed
            else:
                return self.current_page
        else:
            newed = True
            reinit = True
            # 页面的创造只会在这里发生
            if len(page_info.args) != 0:
                widget_contruct_locals = {"page_info": page_info}
                widget_construct_py = "widget_instance = page_info.class_obj("
                for i in range(0, len(page_info.args)):
                    widget_construct_py += "page_info.args[{0}], ".format(i)
                widget_construct_py = widget_construct_py[:-1]
                widget_construct_py += ")"
                exec(widget_construct_py, globals(), widget_contruct_locals)
                widget_instance = widget_contruct_locals["widget_instance"]
            else:
                widget_instance = page_info.class_obj()
            if widget_instance is None:
                raise ValueError("page({0})'swidget instance is None".format(name))
            else:  # 为页面hook适当的一些属性。。。
                widget_instance._wizard = self
                # 大小调整
                if hasattr(widget_instance, "sigAdjustWizardContainerSize"):
                    if hasattr(self.stage, "adjust_wizard_container_size_delegate"):
                        widget_instance.sigAdjustWizardContainerSize.connect(self.stage.adjust_wizard_container_size_delegate)
            self.stage.layout().addWidget(widget_instance)
            self.widgets[name] = widget_instance
        if self.current_page is not None:
            self.current_page.setVisible(False)

        if self.current_page is None:
            pass
        else:
            self.current_page.__next_page__ = widget_instance
        widget_instance.__previous_page__ = self.current_page
        self.current_page = widget_instance
        self.current_page.setVisible(True)
        self.current_page_name = name
        self.sigPageSwitched.emit(name)

        if reinit is True:
            if isinstance(init_arg, tuple) is False:
                init_arg = (init_arg, )
            if len(init_arg) > 0:
                py = "widget_instance.init("
                for i in range(0, len(init_arg)):
                    py += "init_arg[{0}], ".format(i)
                py = py[:-1]
                py += ")"
                exec(py)
            else:
                widget_instance.init()
        if tell_me_new is True:
            return self.current_page, newed
        else:
            return self.current_page